package me.zhangsanfeng.gpss.common.handler;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import me.zhangsanfeng.gpss.common.entity.JwtProperty;
import me.zhangsanfeng.gpss.common.utils.*;
import me.zhangsanfeng.gpss.dao.EmployeeRepository;
import me.zhangsanfeng.gpss.dao.UsersRepository;
import me.zhangsanfeng.gpss.entity.Department;
import me.zhangsanfeng.gpss.entity.Employee;
import me.zhangsanfeng.gpss.entity.Role;
import me.zhangsanfeng.gpss.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录成功处理器
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private JwtProperty jwtProperty;

    public LoginSuccessHandler(JwtProperty jwtProperty){
        this.jwtProperty = jwtProperty;
    }

    private static LoginSuccessHandler loginSuccessHandler;

    @Autowired
    private UsersRepository userRepository;

    @Autowired
    private EmployeeRepository employeeRepository;

    @PostConstruct
    public void init(){
        loginSuccessHandler=this;
        loginSuccessHandler.userRepository=this.userRepository;
        loginSuccessHandler.employeeRepository=this.employeeRepository;
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        String remoteAddr = request.getRemoteAddr();
        response.setContentType("application/json;charset=UTF-8");
        //通过token解析出封装的授权信息
        String auth = response.getHeader("Authorization");
        Claims claims = null;
        try {
            claims = JwtUtil.parseToken(auth.replace("Bearer ", ""),
                    jwtProperty.getBase64Security());
        } catch (Exception e) {
            response.getWriter().write(JsonUtil.toJsonString(ResultUtil.error(e)));
            return;
        }
        String username = claims.get("username").toString();
        Date expiration = claims.getExpiration();
        Date notbefore = claims.getNotBefore();

        String name = null;
        String deptCode = null;
        String deptName = null;
        //取出员工信息
        Employee employee = loginSuccessHandler.employeeRepository.findByPhone(username);
        if (DataUtil.isNotEmpty(employee)){
            name = employee.getName();
            Department department = employee.getDepartment();
            if (DataUtil.isNotEmpty(department)){
                deptCode = department.getCode().toString();
                deptName = department.getName();
            }
        }

        String role = null;
        //记录登录日志
        Users user = loginSuccessHandler.userRepository.findByUsername(username);
        if (DataUtil.isNotEmpty(user)){
            List<Role> roles = user.getRoleList();
            if (DataUtil.isNotEmpty(roles)){
                role = roles.toString();
            }
            user.setLoginTime(DateUtil.currentTimestamp());
            user.setIpAddr(remoteAddr);
            loginSuccessHandler.userRepository.saveAndFlush(user);
        }

        //通过response返回登录成功的token信息
        Map<String,String> map = new HashMap<>();
        map.put("Username", username);
        map.put("Name",name);
        map.put("DeptCode",deptCode);
        map.put("DeptName",deptName);
        map.put("Roles",role);
        map.put("Authorization",auth);
        map.put("Expiration", DateUtil.date2String(expiration,
                DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS));
        map.put("Notbefore",DateUtil.date2String(notbefore,
                DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS));
        response.getWriter().write(JsonUtil.toJsonString(ResultUtil.success(map)));
    }
}
